﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WXYW.BLL;
using WXYW.DAL;
using System.Web.Configuration;

namespace WXYW
{
    public partial class DistributeRMAForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString[Constants.QUERYSTR_APPLICATION_ID] != null)
                {
                    FillServiceStation();
                    FillApplicationProductGridView();
                }
            }
        }

        private void FillApplicationProductGridView()
        {
            ApplicationService serivce = new ApplicationService();
            ApplicationForm applicationForm = serivce.GetApplicationFormDetailByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));

            // bind user information
            applyCompanyNameTxtBox.Text = applicationForm.User.FullName; //ContextService.CurrentAccount.CompanyName;
            mailAddressTxtBox.Text = applicationForm.User.UserAddress; //ContextService.CurrentAccount.UserAddress;
            applierEmailTxtBox.Text = applicationForm.User.UserEmail; //ContextService.CurrentAccount.UserEmail;
            applierFaxTxtBox.Text = applicationForm.User.UserFax; //ContextService.CurrentAccount.UserFax;
            //rmaLabel.Text = applicationForm.ApplicationCode;
            runningNumberLabel.Text = applicationForm.RunningNumber;
            applierNameTxtBox.Text = applicationForm.User.ContactPerson; //ContextService.CurrentAccount.UserName;
            applierPhoneTxtBox.Text = applicationForm.User.UserPhone; //ContextService.CurrentAccount.UserPhone;
            statusLabel.Text = applicationForm.Status;
            if (applicationForm.AgentID != null)
            {
                UserService userservice = new UserService();
                User user = userservice.GetUserByID(applicationForm.AgentID.Value);
                agentLabel.Text = user.ContactPerson;
                agentPhoneLabel.Text = user.UserMobilePhone;
            }

            // bind product
            ProductGridView.DataSource = applicationForm.ApplicationProduct;
            ProductGridView.DataBind();

            if (applicationForm.ReleventRMANO != null && !applicationForm.ReleventRMANO.Equals(""))
            {
                orginRMANoLbl.Visible = true;
                originRMANoBtn.Visible = true;

                originRMANoBtn.Text = applicationForm.ReleventRMANO;
            }
        }

        private void FillServiceStation()
        {
            ApplicationService service = new ApplicationService();
            serviceStationDropDownList.DataSource = service.GetAllServiceStation();
            serviceStationDropDownList.DataTextField = "Name";
            serviceStationDropDownList.DataValueField = "ID";
            serviceStationDropDownList.DataBind();
        }

        protected void productGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            ProductGridView.EditIndex = e.NewEditIndex;
            FillApplicationProductGridView();
            ApplicationProductService service = new ApplicationProductService();
            ApplicationProduct product = service.GetApplicationProductByID(long.Parse(ProductGridView.DataKeys[e.NewEditIndex].Value.ToString()));
            //
            DropDownList typeDDL = (DropDownList)ProductGridView.Rows[e.NewEditIndex].FindControl("typeDropDownList");
            typeDDL.DataSource = service.GetAllProductType();
            typeDDL.DataTextField = "ProductTypeName";
            typeDDL.DataValueField = "ProductTypeID";
            typeDDL.DataBind();
            typeDDL.SelectedValue = product.ProductType.ProductTypeID.ToString();
            //
            DropDownList repairTypeDDL = (DropDownList)ProductGridView.Rows[e.NewEditIndex].FindControl("repairTypeDropDownList");
            repairTypeDDL.Text = product.ProductRepairType;

            DropDownList problemTypeDDL = (DropDownList)ProductGridView.Rows[e.NewEditIndex].FindControl("problemTypeDropDownList");
            ProblemTypeService problemtypeservice = new ProblemTypeService();
            problemTypeDDL.DataSource = problemtypeservice.GetAllProblemType();
            problemTypeDDL.DataTextField = "Name";
            problemTypeDDL.DataValueField = "ID";
            problemTypeDDL.DataBind();
            if (!product.ProblemTypeReference.IsLoaded)
            {
                product.ProblemTypeReference.Load();
            }
            problemTypeDDL.SelectedValue = product.ProblemType.ID.ToString();

            DropDownList versionNumberDDL = (DropDownList)ProductGridView.Rows[e.NewEditIndex].FindControl("VersionNumberDDL");
            versionNumberDDL.SelectedValue = product.ProductVersionNumber;
        }

        protected void productGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            long productID = long.Parse(ProductGridView.DataKeys[e.RowIndex].Value.ToString());
            int productTypeID = Convert.ToInt32(((DropDownList)ProductGridView.Rows[e.RowIndex].FindControl("typeDropDownList")).SelectedValue);
            int amount = Convert.ToInt32(((TextBox)ProductGridView.Rows[e.RowIndex].Cells[3].Controls[0]).Text);
            string productSerialNumber = ((TextBox)ProductGridView.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
            string problemDiscription = ((TextBox)ProductGridView.Rows[e.RowIndex].Cells[5].Controls[0]).Text;
            string productAppearance = ((TextBox)ProductGridView.Rows[e.RowIndex].Cells[6].Controls[0]).Text;
            string repairType = ((DropDownList)ProductGridView.Rows[e.RowIndex].FindControl("repairTypeDropDownList")).Text;
            string versionNumber = ((DropDownList)ProductGridView.Rows[e.RowIndex].FindControl("VersionNumberDDL")).Text;
            int problemTypeID = Convert.ToInt32(((DropDownList)ProductGridView.Rows[e.RowIndex].FindControl("problemTypeDropDownList")).SelectedValue);
            ApplicationProductService service = new ApplicationProductService();
            service.UpdateApplicationProduct(productID, productTypeID, amount, productSerialNumber,
                problemDiscription, productAppearance, "", repairType, problemTypeID, versionNumber);

            ProductGridView.EditIndex = -1;
            FillApplicationProductGridView();
        }

        protected void productGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            ProductGridView.EditIndex = -1;
            FillApplicationProductGridView();
        }

        protected void updateLinkButton_Click(object sender, EventArgs e)
        {
            try
            {
                ApplicationService service = new ApplicationService();
                ApplicationForm form = service.ConfirmRMACode(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]), Convert.ToInt32(serviceStationDropDownList.SelectedValue));
                FillApplicationProductGridView();
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }


                string products = string.Empty;
                foreach (ApplicationProduct product in form.ApplicationProduct)
                {
                    if (!product.ProductTypeReference.IsLoaded)
                    {
                        product.ProductTypeReference.Load();
                    }
                    if (!string.IsNullOrEmpty(products))
                    {
                        products = product.ProductType.ProductTypeName + "," + product.ProductSerialNumber;
                    }
                    else
                    {
                        products += product.ProductType.ProductTypeName + "," + product.ProductSerialNumber;
                    }
                }

                // send email
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }

                ServiceStationService ssService = new ServiceStationService();
                ServiceStation servicestation = ssService.GetServiceStation(Convert.ToInt32(serviceStationDropDownList.SelectedValue));

                string body = string.Format(WebConfigurationManager.AppSettings["ConfirmApplicationCode"], form.User.ContactPerson, products, form.ApplicationCode, servicestation.Address + "," + servicestation.Phone + "," + servicestation.ContactPerson);
                EmailService.SendEmail(form.User.UserEmail, "申请单已确认", body);                
                Response.Write(string.Format("<script language='JavaScript'> alert( '您已成功确认了{0}的申请单。单号为:{1}。');location.href= '{2}' </script> ",
                    form.User.UserName, form.ApplicationCode, "ListRMAForm.aspx"));
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "DistributeRMAForm::updateLinkButton_Click");
            }
        }

        protected void backLinkButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("ListRMAForm.aspx");
        }

        protected void ProductGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem != null)
            {
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FFFF99'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
                ((Label)e.Row.FindControl("IDLbl")).Text = (e.Row.RowIndex + 1).ToString();
            }
        }

        protected void originRMANoBtn_Click(object sender, EventArgs e)
        {
            string back_url = Request.Url.ToString();
            string url = string.Format("RMALinkDetail.aspx?APPLICATIOM_ID={0}&" + Constants.QUERYSTR_BACK_URL + "={1}",
                Request.QueryString[Constants.QUERYSTR_APPLICATION_ID], back_url);
            Response.Redirect(url);
        }
    }
}
